package com.koal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.koal.mapper.AdminMapper;
import com.koal.pojo.Admin;
import com.koal.pojo.ResultBean;
import com.koal.pojo.Salary;
import com.koal.service.IAdminService;
import com.koal.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LuoYQ
 * @since 2021-09-08
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {


    @Value("${jwt.tokenHeader}")
    public String tokenHeader;

    @Autowired
    public UserDetailsService userDetailsService;

    @Autowired
    public PasswordEncoder passwordEncoder;


    @Autowired
    public JwtTokenUtil jwtTokenUtil;

    @Autowired
    public AdminMapper adminMapper;


    /**
     * 返回token
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public ResultBean login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || !passwordEncoder.matches(password,userDetails.getPassword())) {
            return ResultBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            return ResultBean.error("账号被禁用");
        }
        //将认证信息放到Security的上下文
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String,String> hashMap = new HashMap();
        hashMap.put("token",token);
        hashMap.put("tokenHeader",tokenHeader);
        return  ResultBean.success("登录成功",hashMap);
    }

    /**
     * 通过username获得admin
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
    }
}
